package com.zm.demo.oauth2.client.util;

import okhttp3.*;
import okio.BufferedSink;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Map;

public class OkHttpUtil {

    public static Response post(String url, final String contentType, final byte [] body) throws Exception{
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new RequestBody() {
            @Nullable
            @Override
            public MediaType contentType() {
                return MediaType.parse(contentType);
            }

            @Override
            public void writeTo(@NotNull BufferedSink bufferedSink) throws IOException {
                if (body != null) {
                    bufferedSink.write(body);
                }
                bufferedSink.flush();
            }
        };
        Request request = new Request.Builder().url(url.toString()).post(requestBody).build();

        Response response = client.newCall(request).execute();
        return response;
    }

    public static Response get(String url, final Map<String,String> headers) throws Exception{
        OkHttpClient client = new OkHttpClient();
        final Request.Builder builder = new Request.Builder().url(url.toString());
        if ( headers != null && !headers.isEmpty()){
            headers.entrySet().stream().forEach(e -> builder.addHeader(e.getKey(), e.getValue()));
        }

        Request request = builder.get().build();
        Response response = client.newCall(request).execute();
        return response;
    }
}
